package org.dreamwork.tools.network.bridge.client.fx.controllers;

import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.dreamwork.db.IDatabase;
import org.dreamwork.misc.AlgorithmUtil;
import org.dreamwork.network.sshd.data.User;
import org.dreamwork.tools.network.bridge.client.fx.DialogHelp;
import org.dreamwork.tools.network.bridge.client.fx.GuiContext;
import org.dreamwork.util.StringUtil;

/**
 * Created by seth.yang on 2020/3/9
 */
public class LoginController extends AbstractController {
    @FXML private TextField txtUserName;
    @FXML private PasswordField txtPassword;

    @FXML void login () {
        String userName = txtUserName.getText ();
        String password = txtPassword.getText ();

        String sql = "SELECT * FROM t_user WHERE user_name = ?";
        IDatabase database = GuiContext.getDatabase ();
        User user = database.getSingle (User.class, sql, userName);
        if (user != null) {
            byte[] tmp = password.getBytes ();
            try {
                tmp = AlgorithmUtil.md5 (tmp);
                String md5 = StringUtil.byte2hex (tmp, false);
                if (md5.equals (user.getPassword ())) {
                    GuiContext.setCurrentUser (user);
                    // login success
                    cancel ();
                }
            } catch (Exception ex) {
                DialogHelp.error (ex.getMessage (), ex);
            }
        }
    }
}
